package com.coai.message.service

import com.coai.message.model.Message
import com.coai.message.model.MessageType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.springframework.context.event.EventListener
import org.springframework.stereotype.Component

/**
 * 消息事件监听器 - 处理消息相关的AI自动化任务
 */
@Component
class MessageEventListener(
    private val aiMessageService: AIMessageService
) {
    
    /**
     * 监听新消息事件，触发AI自动处理
     */
    @EventListener
    fun onNewMessage(event: MessageCreatedEvent) {
        val message = event.message
        
        // 异步处理AI任务，避免阻塞主流程
        CoroutineScope(Dispatchers.IO).launch {
            try {
                // 1. 智能客服自动回复
                if (shouldAutoReply(message)) {
                    aiMessageService.analyzeAndReply(
                        conversationId = message.conversationId,
                        message = message,
                        userId = message.senderId
                    )
                }
                
                // 2. 情绪分析（用于客服质量监控）
                if (message.messageType == MessageType.TEXT) {
                    val sentiment = aiMessageService.analyzeSentiment(
                        conversationId = message.conversationId,
                        message = message
                    )
                    
                    // 如果检测到负面情绪，发送预警
                    val sentimentScore = sentiment["score"] as? Double ?: 0.0
                    if (sentimentScore < -0.5) {
                        // TODO: 发送预警通知给管理员
                        println("检测到负面情绪，会话: ${message.conversationId}")
                    }
                }
                
            } catch (e: Exception) {
                println("AI消息处理失败: ${e.message}")
            }
        }
    }
    
    /**
     * 判断是否需要自动回复
     */
    private fun shouldAutoReply(message: Message): Boolean {
        // 1. 只对客户消息自动回复
        // 2. 排除AI自己发送的消息
        // 3. 检查是否包含触发关键词
        if (message.senderId == "ai-assistant") return false
        if (message.messageType != MessageType.TEXT) return false
        
        val autoReplyKeywords = listOf(
            "客服", "帮助", "咨询", "问题", "在吗", 
            "价格", "多少钱", "怎么用", "如何", "能不能"
        )
        
        return autoReplyKeywords.any { 
            message.content.contains(it, ignoreCase = true) 
        }
    }
}

/**
 * 消息创建事件
 */
data class MessageCreatedEvent(
    val message: Message
)
